package com.gtl.meishi.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.gtl.meishi.R;
import com.gtl.meishi.adapter.CotegroyAdapter;
import com.gtl.meishi.adapter.HotFragmentAdapter;
import com.gtl.meishi.bean.CotegroyEntity;
import com.gtl.meishi.model.MediaModel;
import com.gtl.meishi.util.HttpURLUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.listener.BmobUpdateListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import cn.bmob.v3.update.UpdateResponse;
import cn.bmob.v3.update.UpdateStatus;

;

/**
 *
 */
public class MainActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private ViewPager mViewPager;
    private TabLayout mTableLayout;
    private HotFragmentAdapter adapter;
    private CotegroyAdapter cotegroyAdapter;//viewpager 和tablelayout公用适配器此处就没用了
    private List<CotegroyEntity> cotegroyEntitylist =new ArrayList<>();
    private NavigationView mNavigationView;
    private DrawerLayout mDrawerLayout;
    UpdateResponse ur;
    public static String APPID = "4385626f2be1bdde82da2e6ad2cebc0e";

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case  0:
                    cotegroyEntitylist= (List<CotegroyEntity>) msg.obj;
                    cotegroyAdapter=new CotegroyAdapter(cotegroyEntitylist,MainActivity.this);
                  // mTableLayout.setTabsFromPagerAdapter(cotegroyAdapter);
                    adapter=new HotFragmentAdapter(getSupportFragmentManager(),MediaModel.getFragement(cotegroyEntitylist));
                     mViewPager.setAdapter(adapter);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化
        init();
        //初始化数据
        InitData();
        //监听器

    }

    /**
     * 初始化数据
     */
    private void InitData() {
        final String url= HttpURLUtil.BASE_URL+HttpURLUtil.CATEGOTY_URL;
        MediaModel.getCotegory(handler,url,this);
    }




    /**
     * 初始化
     */
    private void init() {

        // 初始化BmobSDK
       Bmob.initialize(this, APPID);	//
      //  BmobUpdateAgent.update(this);
            updata();
        mTableLayout= (TabLayout) findViewById(R.id.tablelayout_main);
        mViewPager= (ViewPager) findViewById(R.id.viewpager_main);
        mToolbar= (Toolbar) findViewById(R.id.toolbar_main);
        mNavigationView= (NavigationView) findViewById(R.id.navigation_view_main);
         mDrawerLayout= (DrawerLayout) findViewById(R.id.drawerlayout_main);
        mToolbar.setTitle("美视");
        setSupportActionBar(mToolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        //tabyaout 和viewpager绑定
        mTableLayout.setupWithViewPager(mViewPager);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mViewPager.setCurrentItem(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
       //左侧菜单监听器
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()){

                    case R.id.nav_share:
                       BmobUpdateAgent.update(MainActivity.this);
                        //BmobUpdateAgent.forceUpdate(getApplicationContext());
                        Log.i("TAG",item.getTitle()+"");
                        break;
                    case R.id.nav_collection:
                            Intent intent=new Intent(MainActivity.this,CollectionActivity.class);
                        startActivity(intent);

                        break;
                    case R.id.nav_del:
                            del();
                        break;


                }

                return true;
            }
        });


    }
    @Override// toobar 返回事件监听
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if(item.getItemId() == android.R.id.home)
        {
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true ;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * @param view
     *
     * 注册登录按钮
     */
    public  void doClick(View view){
        Intent intent =new Intent();
        switch (view.getId()){
            case R.id.button_login_main:
                intent.setClass(MainActivity.this,LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.button_regist_main:
                intent.setClass(MainActivity.this,RegistActivity.class);
                startActivity(intent);
                break;
        }


    }

    /**
     * 更新
     */
    public  void  updata(){

        BmobUpdateAgent.setUpdateListener(new BmobUpdateListener() {

            @Override
            public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                // TODO Auto-generated method stub
                if (updateStatus == UpdateStatus.Yes) {
                    ur = updateInfo;
                }else if(updateStatus==UpdateStatus.IGNORED){//新增忽略版本更新
                    Toast.makeText(MainActivity.this, "该版本已经被忽略更新", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    /**
     * 清除下载数据
     */
    public void del(){
        // 删除下载的apk文件
        if(ur != null){
            File file = new File(Environment
                    .getExternalStorageDirectory(), ur.path_md5 + ".apk");
            if (file != null) {
                if (file.delete()) {
                    Toast.makeText(this, "删除完成",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "删除失败",
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MainActivity.this, "删除完成", Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onBackPressed() {
        if(mDrawerLayout.isDrawerOpen(mNavigationView)){
            mDrawerLayout.closeDrawers();
        }else {
            finish();
        }

    }
}
